package com.tulele.vtool.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tulele.vtool.mapper.WxNotifyMsgSetInfoMapper;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.UserBrandCombinedInfo;
import com.tulele.vtool.model.combinedEntity.VidoeListDto;
import com.tulele.vtool.model.logEntity.PageDetailLog;
import com.tulele.vtool.model.reqEntity.GetArticleInfoByArticleBrandForHotScoreReqBean;
import com.tulele.vtool.model.reqEntity.GetRecommendUserInfoReqBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import com.tulele.vtool.utils.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class ConnectionInfoHandler {

   @Autowired
   private ConnectionInfoService connectionInfoService;

   @Autowired
   private IUserInfoService userInfoService;

//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    @Autowired
    private IArticleTypeInfoService articleTypeInfoService;

    @Autowired
    private IUserArticleTypeInfoService userArticleTypeInfoService;

//    @Autowired
//    private WeixinService weixinService;

//    @Autowired
//    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private WxNotifyMsgSetInfoMapper wxNotifyMsgSetInfoMapper;

//    @Value("${applyMessagePushTempID}")
//    private String applyMessagePushTempID;
//
//    @Value("${passesMessagePushTempID}")
//    private String passesMessagePushTempID;
//
//    @Autowired
//    private PlatformSysInfoConfig platformSysInfoConfig;

    private static final String CONNECTIONUSERSTANDARDPREFIX = "CONNECTIONUSERSTANDARDPREFIX:";

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    @Qualifier("redisTemplate")
    public RedisTemplate redisTemplate;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    @Autowired
    private IVipInfoService vipInfoService;


    /**
     * 20200601 yl
     * 人脉广场分页查询用户
     * @param userId
     * @param recommendUserInfoReqBean
     * @return
     */
    @PostMapping(value = "/selectUserList", produces = "application/json;charset=UTF-8")
    public RespData selectUserList(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GetRecommendUserInfoReqBean recommendUserInfoReqBean) {
//        WeixinServiceDL weixinService= objectFactory.getObject();
//        weixinService.reSetConfigStorage(springProfilesActive);

        PlatformSysInfo platformSysInfoConfig = sysGzhService.getPlatformSysInfo(springProfilesActive);
        //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
        WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(springProfilesActive);

        this.addFriendsOnPlatform(Integer.valueOf(userId), springProfilesActive, weixinService);
        Integer pageNum = recommendUserInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = recommendUserInfoReqBean.getPageSize();
        if (pageSize == null || pageSize.intValue() <= 0) {
            pageSize = 10;
        }
        String[] screen = null;
        if (StringUtils.isNotBlank(recommendUserInfoReqBean.getRegion())) {
            screen = StringUtils.split(recommendUserInfoReqBean.getRegion(), ',');
        }
        RespData respData = new RespData();
        List<UserInfo> users = new ArrayList<>();
        if (pageNum.equals(1) && CollectionUtils.isEmpty(recommendUserInfoReqBean.getNeedIds()) && CollectionUtils.isEmpty(recommendUserInfoReqBean.getArticleTypeIds()) && screen == null) {

            // 查询该用户在今天内申请过多少次
            Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("connectionKF_Show" + userId);
            if (lastWxPushTimeObj==null) {
                // 查询userid是否已经添加连个客服
                Integer num1 = this.connectionInfoService.isAdd(Integer.valueOf(userId), 6604494);
                Integer num2 = this.connectionInfoService.isAdd(Integer.valueOf(userId), 2308581);
                if (num1.equals(0)) {
                    users.add(ToolUtil.OneCoster());//插入客服信息
                }
                if (num2.equals(0)) {
                    users.add(ToolUtil.TwoCoster());//插入客服信息
                }
                redisCacheUtil.setCacheObject("connectionKF_Show" + userId, DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss", DateUtil.getCurDate()), 43200);//12小时
            }

            List<UserInfo> usersOne = this.userInfoService.selectUserList(null,
                    null,
                    Integer.valueOf(userId),
                    springProfilesActive,
                    null,
                    null,
                    null);
            users.addAll(usersOne);
            Collections.shuffle(users);//混乱的意思
        } else {
            if (CollectionUtils.isEmpty(recommendUserInfoReqBean.getNeedIds()) && CollectionUtils.isEmpty(recommendUserInfoReqBean.getArticleTypeIds()) && screen == null) {
                pageNum--;
            }

            if (pageNum.equals(1)) {
                // 设置基准用户
                Integer standardUserId = userInfoService.selectStandardUserIdByCreationTimeDesc();
                redisTemplate.opsForValue().set(CONNECTIONUSERSTANDARDPREFIX + userId, standardUserId);
            }
            users = this.userInfoService.selectUserListByRandom(pageNum,
                    pageSize,
                    Integer.valueOf(userId),
                    springProfilesActive,
                    screen,
                    recommendUserInfoReqBean.getNeedIds(),
                    recommendUserInfoReqBean.getArticleTypeIds(),
                    (Integer) redisCacheUtil.getCacheObject(CONNECTIONUSERSTANDARDPREFIX + userId));
        }
        if (CollectionUtils.isNotEmpty(users)) {
            // 将电话设置为*
            respData.setData(users.stream().map(userInfo -> {
                if (StringUtils.isNotBlank(userInfo.getTelNum()) && userInfo.getTelNum().length() > 4) {
                    userInfo.setTelNum(userInfo.getTelNum().replace(userInfo.getTelNum().substring(2, userInfo.getTelNum().length() - 2), "*******"));
                }
                userInfo.setNeedList(this.connectionInfoService.selectNeedNameByUserId(userInfo.getUserId(), springProfilesActive));
                userInfo.setRegion(this.connectionInfoService.selectRegionByUserId(userInfo.getUserId()));
                userInfo.setBrandNames(String.join(",", this.userBrandInfoService.getUserBrandNameInfo(userInfo.getUserId())));
                if (userInfo.getVipStatus() != null && userInfo.getVipStatus() == 1) {
                    userInfo.setVipStatus(1);
                } else {
                    userInfo.setVipStatus(0);
                }
                return userInfo;
            }).collect(Collectors.toList()));
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            // 添加访问记录
            this.addAccessRecord(Integer.valueOf(userId), springProfilesActive);

            // 更新人脉广场最后活跃时间
            this.userInfoService.updateLastConActiveTimeByUserId(Integer.valueOf(userId));
            return respData;
        }
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("暂无数据~");
        return respData;
    }

    /**
     * 异步添加用户访问记录
     * @param userId
     */
    @Async
    void addAccessRecord(Integer userId,String springProfilesActive){
        PageDetailLog log = new PageDetailLog();
        log.setAccessTime(new Date());
        log.setGzhCode(springProfilesActive);
        log.setPageName("人脉广场");
        log.setUserId(userId);
        this.connectionInfoService.addAccessRecord(log);
    }

    /**
     * 定时任务 平台添加好友
     * @param userId
     */
    @Async
    void addFriendsOnPlatform(Integer userId, String springProfilesActive, WxMpServiceImpl weixinService) {

        //20200725 hyl
        try {
            // 查询是否存在地址
            Integer region = this.userInfoService.selectCountRegionByUserId(userId);
            // 如果不存在就添加
            if (null == region || region.equals(0)) {
                String openId = this.userInfoService.getUserOpenId(userId);

                //region （公众号做通）20210902
                UserGroupOpenId ugoId= userGroupGzhService.getUserOpenId(springProfilesActive,userId);
                if(ugoId!=null){
                    openId=ugoId.getOpenId();
                }
                //endregion

                WxMpUser wxMpUser = null;

                wxMpUser = weixinService.getUserService().userInfo(openId);

                if (wxMpUser != null) {
                    UserRegionInfo userRegionInfo = new UserRegionInfo();
                    userRegionInfo.setUserId(userId);
                    userRegionInfo.setGzhCode(springProfilesActive);

                    //微信接口整改，不再返回
//                    userRegionInfo.setProvince(wxMpUser.getProvince());//省
//                    userRegionInfo.setCity(wxMpUser.getCity());//城市
                    this.userInfoService.addRegion(userRegionInfo);
                }
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        // 查询是否首次进入
        Integer num = this.connectionInfoService.notFirstTime(userId);
        if (!num.equals(0)) {
            return;
        }
        Timer mer = new Timer();
        PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
        mer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 平台随机添加好友
                Integer platformUserId = selectPlatformUserId(userId, 0);
                if (null == platformUserId) {
                    return;
                }
                ConnectionApplyInfo connectionApplyInfo = new ConnectionApplyInfo();
                connectionApplyInfo.setId(null);
                connectionApplyInfo.setGzhCode("normal");
                connectionApplyInfo.setConnectionFromUserMsg("您好，加个朋友嘛~一起交流下项目");
                connectionApplyInfo.setConnectionToUserId(Integer.valueOf(userId));
                connectionApplyInfo.setConnectionFromUserId(platformUserId);
                connectionApplyInfo.setApplyTime(DateUtil.getCurDate());
                connectionInfoService.sendApply(connectionApplyInfo);
                applyMessagePush(connectionApplyInfo.getConnectionFromUserId(), connectionApplyInfo.getConnectionToUserId(),platformSysInfoConfig,weixinService);
            }
        }, 7200000);
        mer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 平台随机添加好友
                Integer platformUserId = selectPlatformUserId(userId, 0);
                if (null == platformUserId) {
                    return;
                }
                ConnectionApplyInfo connectionApplyInfo = new ConnectionApplyInfo();
                connectionApplyInfo.setId(null);
                connectionApplyInfo.setGzhCode("normal");
                connectionApplyInfo.setConnectionFromUserMsg("您好，加个朋友嘛~一起交流下项目");
                connectionApplyInfo.setConnectionToUserId(Integer.valueOf(userId));
                connectionApplyInfo.setConnectionFromUserId(platformUserId);
                connectionApplyInfo.setApplyTime(DateUtil.getCurDate());
                connectionInfoService.sendApply(connectionApplyInfo);
                applyMessagePush(connectionApplyInfo.getConnectionFromUserId(), connectionApplyInfo.getConnectionToUserId(),platformSysInfoConfig,weixinService);
                // 第二个执行完后关闭线程
                mer.cancel();
            }
        }, 36000000);
    }
    /**
     * 查询出为添加的平台用户
     * @param userId
     * @return
     */
    private Integer selectPlatformUserId(Integer userId,int flag){
        if (flag > 10){
            return null;
        }
        // 平台微信
        // ljt 20201201 换自动添加客服 （旧）183043 玲子 ==> （新）183206 社交营销导师 苏曼 =》182955
        List<Integer> userids = Arrays.asList(182955,6424432,2309894);
        Random rand = new Random();
        Integer platformUserId = userids.get(rand.nextInt(3));
        // 查询生成的userid是否已经添加
        Integer num = this.connectionInfoService.isAdd(userId,platformUserId);
        if (num.equals(0)){
            return platformUserId;
        }
        flag++;
        return selectPlatformUserId(userId,flag);
    }
    /**
     * yl 20200601
     * 发送申请添加好友
     * @param userId
     * @param connectionApplyInfo
     * @return
     */
    @PostMapping(value = "/sendApply", produces = "application/json;charset=UTF-8")
    public RespData sendApply(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody ConnectionApplyInfo connectionApplyInfo) {
        RespData respData = new RespData();

        PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
//        WeixinServiceDL weixinService= objectFactory.getObject();
//        weixinService.reSetConfigStorage(springProfilesActive);
        //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
        WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

        //过滤两个客服
        if(connectionApplyInfo.getConnectionToUserId() == 6604494 || connectionApplyInfo.getConnectionToUserId() == 2308581) {
            //查询是否发送过申请 并且还未同意的
            Integer id = this.connectionInfoService.selectSendApplyId(Integer.valueOf(userId),connectionApplyInfo.getConnectionToUserId(),springProfilesActive);
            if (null != id ){
                // 如果申请过
                connectionApplyInfo.setId(id);
                connectionApplyInfo.setApplyTime(DateUtil.getCurDate());
                if(springProfilesActive.equals("prodqkb")
                        || springProfilesActive.equals("prodqkbpro")
                        || springProfilesActive.equals("prodzgts")
                        || springProfilesActive.equals("prodhyxt")
                        || springProfilesActive.equals("prodhysck")
                        || springProfilesActive.equals("prodshjj")
                        || springProfilesActive.equals("prodshsck")
                        || springProfilesActive.equals("prodkdbw")
                        || springProfilesActive.equals("prodkdbj")
                        || springProfilesActive.equals("prodzzsq")
                        || springProfilesActive.equals("prodtjs")
                        || springProfilesActive.equals("prodbkwz")
                        || springProfilesActive.equals("normal")
                ) {
                    connectionApplyInfo.setConnectionIsPasses(1);//申请通过 20210504
                    connectionApplyInfo.setPassesTime(DateUtil.getCurDate());//申请通过 20210504
                }
                this.connectionInfoService.updateApply(connectionApplyInfo);
                respData.setCode(ReturnCode.NORMAL_SUCC);
                respData.setData(2);
                respData.setMsg("成功");
                // 申请成功发送消息推送
                this.applyMessagePush(Integer.valueOf(userId),connectionApplyInfo.getConnectionToUserId(),platformSysInfoConfig,weixinService);
                return respData;
            }
            // 申请添加好友
            connectionApplyInfo.setId(null);
            connectionApplyInfo.setGzhCode("normal");
            connectionApplyInfo.setConnectionFromUserId(Integer.valueOf(userId));
            connectionApplyInfo.setApplyTime(DateUtil.getCurDate());
            if(springProfilesActive.equals("prodqkb")
                    || springProfilesActive.equals("prodqkbpro")
                    || springProfilesActive.equals("prodzgts")
                    || springProfilesActive.equals("prodhyxt")
                    || springProfilesActive.equals("prodhysck")
                    || springProfilesActive.equals("prodshjj")
                    || springProfilesActive.equals("prodshsck")
                    || springProfilesActive.equals("prodkdbw")
                    || springProfilesActive.equals("prodkdbj")
                    || springProfilesActive.equals("prodzzsq")
                    || springProfilesActive.equals("prodtjs")
                    || springProfilesActive.equals("prodbkwz")
                    || springProfilesActive.equals("normal")
            ) {
                connectionApplyInfo.setConnectionIsPasses(1);//申请通过 20210504
                connectionApplyInfo.setPassesTime(DateUtil.getCurDate());//申请通过 20210504
            }
            this.connectionInfoService.sendApply(connectionApplyInfo);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setData(2);
            respData.setMsg("成功");
            // 申请成功发送消息推送
            this.applyMessagePush(Integer.valueOf(userId),connectionApplyInfo.getConnectionToUserId(),platformSysInfoConfig,weixinService);
            return respData;
        }

        // 查询登录用户是否为vip
        Integer vipStatus = Optional.ofNullable(this.userInfoService.getUserVipStatus(Integer.valueOf(userId))).orElse(0);
        Integer userDayFriendCount = null;
        if (vipStatus.intValue() == 0) {
            // 查询用户（非会员）权限
            ConnectionPermissionInfo connectionPermissionInfo = this.connectionInfoService.selectPermission(springProfilesActive,vipStatus);
            userDayFriendCount = connectionPermissionInfo.getApplyPassesNum();
        } else if (vipStatus.intValue() == 1) {
            // 查询用户（会员）权限
            UserVipValidInfo userVipValidInfoInDB = vipInfoService.getVipValidInfo(Integer.valueOf(userId));
            userDayFriendCount = userVipValidInfoInDB.getDayFriendCount();
        }
        // 查询该用户在今天内申请过多少次
        Integer applyNum = this.connectionInfoService.selectApplyNumByUserId(Integer.valueOf(userId));
        if (applyNum.compareTo(userDayFriendCount) >= 0){
            // 今天申请次数已经用完
            respData.setCode(ReturnCode.SERVER_ERROR);
            respData.setData(0);
            respData.setMsg("次数已用完");
            return respData;
        }
        // 被添加人是否为vip
        Integer vipStatusToUser = Optional.ofNullable(this.userInfoService.getUserVipStatus(connectionApplyInfo.getConnectionToUserId())).orElse(0);
        // 被添加人用户权限
        ConnectionPermissionInfo connectionPermissionInfoToUser = this.connectionInfoService.selectPermission(springProfilesActive,vipStatusToUser);
        // 查询被添加人 今天被添加次数
        /** ljt 屏蔽于 20201201 start*/
//        Integer applyNumToUser = this.connectionInfoService.selectBeAddedNumByUserId(connectionApplyInfo.getConnectionToUserId());
//        if (applyNumToUser.compareTo(connectionPermissionInfoToUser.getBeAddedNum()) >= 0) {
//            // 被添加人今天被申请次数已经用完
//            respData.setCode(ReturnCode.SERVER_ERROR);
//            respData.setData(1);
//            respData.setMsg("次数已用完");
//            return respData;
//        }
        /** ljt 屏蔽于 20201201 end*/
        //查询是否发送过申请 并且还未同意的
        Integer id = this.connectionInfoService.selectSendApplyId(Integer.valueOf(userId),connectionApplyInfo.getConnectionToUserId(),springProfilesActive);
        if (null != id ){
            // 如果申请过
            connectionApplyInfo.setId(id);
            connectionApplyInfo.setApplyTime(DateUtil.getCurDate());
            connectionApplyInfo.setConnectionIsPasses(1);//申请通过 20210504
            connectionApplyInfo.setPassesTime(DateUtil.getCurDate());//申请通过 20210504
            this.connectionInfoService.updateApply(connectionApplyInfo);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setData(2);
            respData.setMsg("成功");
            // 申请成功发送消息推送
            this.applyMessagePush(Integer.valueOf(userId),connectionApplyInfo.getConnectionToUserId(),platformSysInfoConfig,weixinService);
            return respData;
        }

        // 申请添加好友
        connectionApplyInfo.setId(null);
        connectionApplyInfo.setGzhCode("normal");
        connectionApplyInfo.setConnectionFromUserId(Integer.valueOf(userId));
        connectionApplyInfo.setApplyTime(DateUtil.getCurDate());
        if(springProfilesActive.equals("prodqkb")
                || springProfilesActive.equals("prodqkbpro")
                || springProfilesActive.equals("prodzgts")
                || springProfilesActive.equals("prodhyxt")
                || springProfilesActive.equals("prodhysck")
                || springProfilesActive.equals("prodshjj")
                || springProfilesActive.equals("prodshsck")
                || springProfilesActive.equals("prodkdbw")
                || springProfilesActive.equals("prodkdbj")
                || springProfilesActive.equals("prodzzsq")
                || springProfilesActive.equals("prodtjs")
                || springProfilesActive.equals("prodbkwz")
                || springProfilesActive.equals("normal")
        ) {
            connectionApplyInfo.setConnectionIsPasses(1);//申请通过 20210504
            connectionApplyInfo.setPassesTime(DateUtil.getCurDate());//申请通过 20210504
        }
        this.connectionInfoService.sendApply(connectionApplyInfo);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(2);
        respData.setMsg("成功");
        // 申请成功发送消息推送
        this.applyMessagePush(Integer.valueOf(userId),connectionApplyInfo.getConnectionToUserId(),platformSysInfoConfig,weixinService);
        return respData;
    }
    /*
     * 申请之后 进行模板消息推送
     * @param userId
     * @param toUserInfoId
     */
    @Async
    void applyMessagePush(Integer userId, Integer toUserInfoId, PlatformSysInfo platformSysInfo, WxMpServiceImpl weixinService) {
        UserInfo user = this.userInfoService.getUserMainInfo(userId);
        UserInfo toUserInfo = this.userInfoService.getUserMainInfo(toUserInfoId);

        //region （公众号做通）20210902
        if(toUserInfo!=null && !toUserInfo.getGzhCode().equals(platformSysInfo.getSysGzh().getGzhCode())){
            UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(platformSysInfo.getSysGzh().getGzhCode(),toUserInfoId);
            if(userGroupOpenId!=null){
                toUserInfo.setOpenId(userGroupOpenId.getOpenId());
            }
        }
        //endregion

        //if (wxNotifyMsgSetInfoInDB != null && wxNotifyMsgSetInfoInDB.getConnectionMsgStatus().equals(1)) {  //20210726 改成 不判断
            if (toUserInfo.getOpenId() != null) {

                String gzhCode = platformSysInfo.getSysGzh().getGzhCode();
                if (gzhCode.equals("normal")
                        && gzhCode.equals("prodbst")
                        && gzhCode.equals("prodhkbw")
                        && gzhCode.equals("prodbkwz")
                        && gzhCode.equals("prodshjj")
                        && gzhCode.equals("prodshsck")
                        && gzhCode.equals("prodhyxt")
                        && gzhCode.equals("prodhysck")
                        && gzhCode.equals("prodtjs")
                        && gzhCode.equals("prodzzsq")
                        && gzhCode.equals("normal")
                ) {
                    List<UserBrandCombinedInfo> ubList = userBrandInfoService.getUserBrandInfo(toUserInfo.getUserId());

                    String toUserBrand = "";
                    if (ubList != null && ubList.size() > 0) {
                        toUserBrand = ubList.get(0).getBrandName();
                    }

                    // 发送模板消息接口
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            // 接收者openid
                            .toUser(toUserInfo.getOpenId())
                            .templateId(platformSysInfo.getSysGzh().getApplyMessagePushTempId())
                            // 模板跳转链接
                            .url(platformSysInfo.getConnectionPlazaUrl() + "?return=0")//跳到 我的人脉
                            .build();
                    String firstMsg = "⭕ 您有一条新的客户需求待领取：";

                    String[] m_arr = {
                            "我想了解【" + toUserBrand + "】，加个微信？\n" +
                                    "\n" +
                                    "点击这里加她聊聊>>\n" +
                                    "\n" +
                                    "如果给您带来不便，回复81，取消推送消息。",

                            "咨询购买产品\n" +
                                    "\n" +
                                    "点击这里回复她>>\n" +
                                    "\n" +
                                    "如果给您带来不便，回复81，取消推送消息。"
                    };

                    int index = (int) (Math.random() * m_arr.length);
                    String remarkMsg = m_arr[index];

                    String telNum = (user.getTelNum() == null ? "***********" : user.getTelNum());
                    if (telNum.length() >= 3) {
                        telNum = telNum.substring(0, 3) + "********";
                    }

                    // 添加模板数据
                    templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                            .addData(new WxMpTemplateData("keyword1", user.getNickName(), "#A9A9A9"))
                            .addData(new WxMpTemplateData("keyword2", telNum, "#A9A9A9"))
                            .addData(new WxMpTemplateData("keyword3", DateUtil.getFormatDate(null, new Date()), "#A9A9A9"))
                            .addData(new WxMpTemplateData("remark", remarkMsg, "#FF0000"));
                    String msgId = null;
                    try {
                        // 发送模板消息
                        msgId = weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (WxErrorException e) {
                        //e.printStackTrace();
                    }
                } else {

                    String connectionPlazaUrl = platformSysInfo.getConnectionPlazaUrl();
                    if (!gzhCode.equals("prodqkb")
                        && !gzhCode.equals("prodqkbpro")
                            && !gzhCode.equals("prodzgts")
                            && !gzhCode.equals("prodhyxt")
                            && !gzhCode.equals("prodhysck")
                            && !gzhCode.equals("prodshjj")
                            && !gzhCode.equals("prodshsck")
                            && !gzhCode.equals("prodkdbw")
                            && !gzhCode.equals("prodkdbj")
                            && !gzhCode.equals("prodzzsq")
                            &&  !gzhCode.equals("prodtjs")
                            &&  !gzhCode.equals("prodbkwz")
                            && !gzhCode.equals("normal")) { //申请好友直接通过
                        connectionPlazaUrl = connectionPlazaUrl + "?return=0";
                    }

                    // 发送模板消息接口
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            // 接收者openid
                            .toUser(toUserInfo.getOpenId())
                            .templateId(platformSysInfo.getSysGzh().getApplyMessagePushTempId())
                            // 模板跳转链接
                            .url(connectionPlazaUrl)//跳到 我的人脉
                            .build();
                    String firstMsg = "您好，有人加您为好友哦⭕";
                    String remarkMsg = "回复数字【 2 】进入人脉广场";

                    // 添加模板数据
                    templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                            .addData(new WxMpTemplateData("keyword1", user.getNickName(), "#A9A9A9"))
                            .addData(new WxMpTemplateData("keyword2", "添加好友", "#A9A9A9"))
                            .addData(new WxMpTemplateData("keyword3", DateUtil.getFormatDate(null, new Date()), "#A9A9A9"))
                            .addData(new WxMpTemplateData("remark", remarkMsg, "#FF0000"));
                    String msgId = null;
                    try {
                        // 发送模板消息
                        msgId = weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (WxErrorException e) {
                        //e.printStackTrace();
                    }
                }
            }
        //}
    }

    /**
     * yl 20200601
     * 分页查询已经添加的好友
     * @param userId
     * @param recommendUserInfoReqBean
     * @return
     */
    @PostMapping(value = "/selectPassesUserList", produces = "application/json;charset=UTF-8")
    public RespData selectPassesUserList(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GetRecommendUserInfoReqBean recommendUserInfoReqBean) {
        Integer pageNum = recommendUserInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = recommendUserInfoReqBean.getPageSize();
        if (pageSize == null || pageSize.intValue() <= 0) {
            pageSize = 10;
        }
        String[] screen = null;
        if (StringUtils.isNotBlank(recommendUserInfoReqBean.getRegion())){
            screen = StringUtils.split(recommendUserInfoReqBean.getRegion(),',');
        }
        RespData respData = new RespData();
        // 分页查询好友id
        List<ConnectionApplyInfo> connectionApplyInfos = this.connectionInfoService.selectPassesUserListByUserId(Integer.valueOf(userId),pageNum,pageSize,recommendUserInfoReqBean,springProfilesActive,screen);
        if (CollectionUtils.isNotEmpty(connectionApplyInfos)){
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");

            List<UserInfo> users = new ArrayList<>();
            for (ConnectionApplyInfo connectionApplyInfo:connectionApplyInfos) {
                UserInfo userMainInfo = this.userInfoService.getUserMainInfo(connectionApplyInfo.getConnectionFromUserId());
                if(userMainInfo!=null) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setUserId(userMainInfo.getUserId());
                    userInfo.setNickName(userMainInfo.getNickName());
                    userInfo.setAvatarUrl(userMainInfo.getAvatarUrl());
                    userInfo.setTelNum(userMainInfo.getTelNum());
                    userInfo.setConnectionId(connectionApplyInfo.getId());
                    userInfo.setQrcodeUrl(userMainInfo.getQrcodeUrl());
                    userInfo.setBrandNames(String.join(",", this.userBrandInfoService.getUserBrandNameInfo(userInfo.getUserId())));
                    userInfo.setRegion(connectionApplyInfo.getRegion());
                    userInfo.setNeedList(this.connectionInfoService.selectNeedNameByUserId(userInfo.getUserId(), springProfilesActive));
                    users.add(userInfo);
                }
            }
            respData.setData(users);

//            respData.setData(connectionApplyInfos.stream().map(connectionApplyInfo->{
//                UserInfo userMainInfo = this.userInfoService.getUserMainInfo(connectionApplyInfo.getConnectionFromUserId());
//                UserInfo userInfo = new UserInfo();
//                userInfo.setUserId(userMainInfo.getUserId());
//                userInfo.setNickName(userMainInfo.getNickName());
//                userInfo.setAvatarUrl(userMainInfo.getAvatarUrl());
//                userInfo.setTelNum(userMainInfo.getTelNum());
//                userInfo.setConnectionId(connectionApplyInfo.getId());
//                userInfo.setQrcodeUrl(userMainInfo.getQrcodeUrl());
//                userInfo.setBrandNames(String.join(",", this.userBrandInfoService.getUserBrandNameInfo(userInfo.getUserId())));
//                userInfo.setRegion(connectionApplyInfo.getRegion());
//                userInfo.setNeedList(this.connectionInfoService.selectNeedNameByUserId(userInfo.getUserId(),springProfilesActive));
//                return userInfo;
//            }).collect(Collectors.toList()));
            return respData;
        }
        respData.setCode(ReturnCode.NORMAL_SUCC);
        return respData;
    }

    /**
     * yl 20200602
     * 分页查询申请加我的
     * @param userId
     * @param recommendUserInfoReqBean
     * @return
     */
    @PostMapping(value = "/selectToUserList", produces = "application/json;charset=UTF-8")
    public RespData selectToUserList(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GetRecommendUserInfoReqBean recommendUserInfoReqBean) {
        Integer pageNum = recommendUserInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = recommendUserInfoReqBean.getPageSize();
        if (pageSize == null || pageSize.intValue() <= 0) {
            pageSize = 10;
        }

        String[] screen = null;
        if (StringUtils.isNotBlank(recommendUserInfoReqBean.getRegion())) {
            screen = StringUtils.split(recommendUserInfoReqBean.getRegion(), ',');
        }

        RespData respData = new RespData();
        // 查询申请者id以及申请者发送的消息
        List<ConnectionApplyInfo> connectionApplyInfos = this.connectionInfoService.selectToUserListByUserId(Integer.valueOf(userId), pageNum, pageSize, recommendUserInfoReqBean, springProfilesActive, screen);
        if (CollectionUtils.isNotEmpty(connectionApplyInfos)) {
            Map<String, Object> returnMap = Maps.newHashMap();

            List<UserInfo> users = new ArrayList<>();
            for (ConnectionApplyInfo cai : connectionApplyInfos) {
                UserInfo userMainInfo = this.userInfoService.getUserMainInfo(cai.getConnectionFromUserId());
                if (userMainInfo != null) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setUserId(userMainInfo.getUserId());
                    userInfo.setNickName(userMainInfo.getNickName());
                    userInfo.setAvatarUrl(userMainInfo.getAvatarUrl());
                    userInfo.setConnectionId(cai.getId());
                    userInfo.setFromUserMsg(cai.getConnectionFromUserMsg());
                    users.add(userInfo);
                }
            }

            returnMap.put("users", users);
            returnMap.put("count", this.connectionInfoService.selectCountToUserListByUserId(Integer.valueOf(userId), springProfilesActive));
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            respData.setData(returnMap);
            return respData;
        }
        respData.setCode(ReturnCode.NORMAL_SUCC);
        return respData;
    }

    /**
     * yl 20200608
     * 分页查询我申请的 并且还不是好友
     * @param userId
     * @param recommendUserInfoReqBean
     * @return
     */
    @PostMapping(value = "/selectFromUserList", produces = "application/json;charset=UTF-8")
    public RespData selectFromUserList(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GetRecommendUserInfoReqBean recommendUserInfoReqBean) {
        Integer pageNum = recommendUserInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = recommendUserInfoReqBean.getPageSize();
        if (pageSize == null || pageSize.intValue() <= 0) {
            pageSize = 10;
        }

        String[] screen = null;
        if (StringUtils.isNotBlank(recommendUserInfoReqBean.getRegion())) {
            screen = StringUtils.split(recommendUserInfoReqBean.getRegion(), ',');
        }

        RespData respData = new RespData();
        // 查询被申请者id以及申请者发送的消息
        List<ConnectionApplyInfo> connectionApplyInfos = this.connectionInfoService.selectFromUserListByUserId(Integer.valueOf(userId), pageNum, pageSize, recommendUserInfoReqBean, springProfilesActive, screen);
        if (CollectionUtils.isNotEmpty(connectionApplyInfos)) {
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");

            List<UserInfo> users = new ArrayList<>();
            for (ConnectionApplyInfo cai : connectionApplyInfos) {
                UserInfo userMainInfo = this.userInfoService.getUserMainInfo(cai.getConnectionToUserId());
                if (userMainInfo != null) {
                    UserInfo userInfo = new UserInfo();
                    userInfo.setUserId(userMainInfo.getUserId());
                    userInfo.setNickName(userMainInfo.getNickName());
                    userInfo.setAvatarUrl(userMainInfo.getAvatarUrl());
                    userInfo.setConnectionId(cai.getId());
                    userInfo.setRegion(cai.getRegion());
                    if (StringUtils.isNotBlank(userMainInfo.getTelNum()) && userMainInfo.getTelNum().length() > 4) {
                        userInfo.setTelNum(userMainInfo.getTelNum().replace(userMainInfo.getTelNum().substring(2, userMainInfo.getTelNum().length() - 2), "*******"));
                    }
                    userInfo.setBrandNames(String.join(",", this.userBrandInfoService.getUserBrandNameInfo(userInfo.getUserId())));
                    userInfo.setNeedList(this.connectionInfoService.selectNeedNameByUserId(userInfo.getUserId(), springProfilesActive));

                    users.add(userInfo);
                }
            }
            respData.setData(users);

//            respData.setData(connectionApplyInfos.stream().map(connectionApplyInfo->{
//                UserInfo userMainInfo = this.userInfoService.getUserMainInfo(connectionApplyInfo.getConnectionToUserId());
//                UserInfo userInfo = new UserInfo();
//                userInfo.setUserId(userMainInfo.getUserId());
//                userInfo.setNickName(userMainInfo.getNickName());
//                userInfo.setAvatarUrl(userMainInfo.getAvatarUrl());
//                userInfo.setConnectionId(connectionApplyInfo.getId());
//                userInfo.setRegion(connectionApplyInfo.getRegion());
//                if (StringUtils.isNotBlank(userMainInfo.getTelNum()) && userMainInfo.getTelNum().length() > 4){
//                    userInfo.setTelNum(userMainInfo.getTelNum().replace(userMainInfo.getTelNum().substring(2,userMainInfo.getTelNum().length() - 2), "*******"));
//                }
//                userInfo.setBrandNames(String.join(",", this.userBrandInfoService.getUserBrandNameInfo(userInfo.getUserId())));
//                userInfo.setNeedList(this.connectionInfoService.selectNeedNameByUserId(userInfo.getUserId(),springProfilesActive));
//                return userInfo;
//            }).collect(Collectors.toList()));
//            return respData;
        }
        respData.setCode(ReturnCode.NORMAL_SUCC);
        return respData;
    }
    /**
     * yl 20200602
     * 根据id删除好友
     * @param userId
     * @param
     * @return
     */
    @PostMapping(value = "/deleteUserByConnectionId", produces = "application/json;charset=UTF-8")
    public RespData deleteUserByConnectionId(@RequestHeader("userId") String userId, @RequestBody ConnectionApplyInfo connectionApplyInfo) {
        this.connectionInfoService.deleteUserByConnectionId(connectionApplyInfo.getId());
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * yl 20200602
     * 通过好友申请
     * @param userId
     * @param connectionApplyInfo
     * @return
     */
    @PostMapping(value = "/passesUser", produces = "application/json;charset=UTF-8")
    public RespData passesUser(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody ConnectionApplyInfo connectionApplyInfo) {
        // 查询登录用户是否为vip
        Integer vipStatus = Optional.ofNullable(this.userInfoService.getUserVipStatus(Integer.valueOf(userId))).orElse(0);
        // 查询 用户权限
        ConnectionPermissionInfo connectionPermissionInfo = this.connectionInfoService.selectPermission(springProfilesActive,vipStatus);
        // 查询该用户在今天内通过次数
        Integer passesNum = this.connectionInfoService.selectPassesNumByUserId(Integer.valueOf(userId));
        RespData respData = new RespData();
        if (passesNum.compareTo(connectionPermissionInfo.getPassesNum()) >= 0){
            // 今天通过次数已经用完
            respData.setCode(ReturnCode.SERVER_ERROR);
            respData.setData(0);
            respData.setMsg("次数已用完");
            return respData;
        }
        // 通过添加好友申请
        this.connectionInfoService.passesUser(connectionApplyInfo.getId());
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(1);
        // 发送申请通过通知
        ConnectionApplyInfo connectionInfo =this.connectionInfoService.selectToUserIdByNeedId(connectionApplyInfo.getId());

//        WeixinServiceDL weixinService= objectFactory.getObject();
//        weixinService.reSetConfigStorage(springProfilesActive);
        PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
        //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
        WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);
        this.passesMessagePush(connectionInfo.getConnectionFromUserId(),connectionInfo.getConnectionToUserId(), platformSysInfoConfig,weixinService);
        return respData;
    }
    /*
     * 申请通过 进行模板消息推送
     * @param userId
     * @param toUserInfoId
     */
    @Async
    void passesMessagePush(Integer fromUserInfoId, Integer toUserInfoId, PlatformSysInfo platformSysInfo, WxMpServiceImpl weixinService) {
        UserInfo toUserInfo = this.userInfoService.getUserMainInfo(toUserInfoId);
        UserInfo fromUserInfo = this.userInfoService.getUserMainInfo(fromUserInfoId);

        //region （公众号做通）20210902
        if(fromUserInfo!=null && !fromUserInfo.getGzhCode().equals(platformSysInfo.getSysGzh().getGzhCode())){
            UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(platformSysInfo.getSysGzh().getGzhCode(),fromUserInfoId);
            if(userGroupOpenId!=null){
                fromUserInfo.setOpenId(userGroupOpenId.getOpenId());
            }
        }
        //endregion

        if (fromUserInfo.getOpenId() != null) {

            // 发送模板消息接口
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    // 接收者openid
                    .toUser(fromUserInfo.getOpenId())
                    // 模板id
                    //.templateId(passesMessagePushTempID)
                    .templateId(platformSysInfo.getSysGzh().getPassesMessagePushTempId())
                    // 模板跳转链接
                    //.url(platformSysInfoConfig.getConnectionPlazaUrl())
                    .url(platformSysInfo.getConnectionPlazaUrl()+"?return=0")//跳到 我的人脉
                    .build();
            String firstMsg ="您的好友申请已通过⭕";
            String remarkMsg = "回复数字【 2 】进入人脉广场";

            // 添加模板数据
            templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword1", toUserInfo.getNickName(), "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword2", toUserInfo.getNickName()+"同意了您的好友请求", "#A9A9A9"))
                    .addData(new WxMpTemplateData("remark", remarkMsg, "#FF0000"));
            String msgId = null;
            try {
                // 发送模板消息
                msgId = weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            } catch (WxErrorException e) {
                //e.printStackTrace();
            }

        }


    }

    /**
     * yl 20200602
     * 查询自己的资料
     * @param userId
     * @param
     * @return
     */
    @PostMapping(value = "/selectUserByUserId", produces = "application/json;charset=UTF-8")
    public RespData selectUserByUserId(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {
        // 查询个人资料
        UserInfo userMainInfo = this.userInfoService.getUserMainInfo(Integer.valueOf(userId));
        Map<String,Object> map = Maps.newHashMap();
        if (null != userMainInfo){
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userMainInfo.getUserId());
            userInfo.setNickName(userMainInfo.getNickName());
            userInfo.setAvatarUrl(userMainInfo.getAvatarUrl());
            userInfo.setTelNum(userMainInfo.getTelNum());
            userInfo.setQrcodeUrl(userMainInfo.getQrcodeUrl());
            // 查询用户地址
            userInfo.setRegion(this.connectionInfoService.selectRegionByUserId(userInfo.getUserId()));
            // 查询自己是否能够被添加
            Integer connectionIsBeAdded = this.connectionInfoService.selectWhetherOrBeAdded(userInfo.getUserId());
            if (null != connectionIsBeAdded){
                userInfo.setConnectionIsBeAdded(connectionIsBeAdded);
            }else {
                // 不存在权限数据将默认能够添加
                userInfo.setConnectionIsBeAdded(1);
                WxNotifyMsgSetInfo wxNotifyMsgSetInfo = new WxNotifyMsgSetInfo();
                wxNotifyMsgSetInfo.setUserId(userInfo.getUserId());
                wxNotifyMsgSetInfo.setCreateTime(DateUtil.getCurDate());
                this.connectionInfoService.addWhetherOrBeAdded(wxNotifyMsgSetInfo);
            }

            // 查询用户关注的品牌
            userInfo.setBrandNames(String.join(",", this.userBrandInfoService.getUserBrandNameInfo(userInfo.getUserId())));
            userInfo.setNeedList(this.connectionInfoService.selectNeedNameByUserId(userInfo.getUserId(),springProfilesActive));
            map.put("userInfo",userInfo);
        }
        // 查询人脉广场权限
        Integer vipStatus = Optional.ofNullable(this.userInfoService.getUserVipStatus(Integer.valueOf(userId))).orElse(0);
        ConnectionPermissionInfo connectionPermissionInfo = this.connectionInfoService.selectPermission(springProfilesActive,vipStatus);
        if (vipStatus.intValue() == 1) {
            // 查询用户每日添加好友的次数
            UserVipValidInfo userVipValidInfoInDB = vipInfoService.getVipValidInfo(Integer.valueOf(userId));
            connectionPermissionInfo.setApplyPassesNum(userVipValidInfoInDB.getDayFriendCount());// 重新赋值 2021-09-28
        }
        map.put("permission",connectionPermissionInfo);
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(map);
        return respData;
    }

    /**
     * 切换自己隐身
     * @param userId
     * @return
     */
    @PostMapping(value = "/switchState", produces = "application/json;charset=UTF-8")
    public RespData switchState(@RequestHeader("userId") String userId) {
        // 查询用户是否隐身
        RespData respData = new RespData();
        Integer state = this.connectionInfoService.selectWhetherOrBeAdded(Integer.valueOf(userId)) == 1 ? 0 : 1;
        this.connectionInfoService.switchState(Integer.valueOf(userId),state);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 查询基础需求
     * yl 20200611
     * @param userId
     * @return
     */
    @PostMapping(value = "/selectNeedByGzhCode", produces = "application/json;charset=UTF-8")
    public RespData selectNeedByGzhCode(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {
        Map<String,List<ConnectionNeedInfo>> connectionNeedInfoMap = this.connectionInfoService.selectNeedByGzhCode(springProfilesActive);
        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(connectionNeedInfoMap);
        return respData;
    }

    /**
     * 用户设置需求
     * yl 20200611
     * @param userId
     * @return
     */
    @PostMapping(value = "/setNeedByUserId", produces = "application/json;charset=UTF-8")
    public RespData setNeedByUserId(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive,@RequestBody ConnectionUserNeedInfo connectionUserNeedInfo) {
        RespData respData = new RespData();
        if (null == connectionUserNeedInfo || CollectionUtils.isEmpty(connectionUserNeedInfo.getNeedIds())){
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("请选择您的身份及需求");
            return respData;
        }
        //查询是否超出上限 身份、需求分别只能设置5个
        Integer beyond = this.connectionInfoService.selectNeedBeyond(connectionUserNeedInfo.getNeedIds());
        if (beyond.equals(1)){
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("身份、需求分别只能设置5个");
            return respData;
        }

        String phoneNumber = connectionUserNeedInfo.getTelNum();

        if (StringUtils.isNotBlank(phoneNumber)) {
            if (phoneNumber.length() != 11) {
                respData.setCode(ReturnCode.CLIENT_ERROR);
                respData.setMsg("手机号应为11位数~");
                return respData;
            }

            String regex = "^(1[3-9]\\d{9}$)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phoneNumber);
            boolean isMatch = m.matches();
            if (!isMatch) {
                respData.setCode(ReturnCode.CLIENT_ERROR);
                respData.setMsg("手机号格式不正确~");
                return respData;
            }

            // 查询用户基础信息
            Integer userIdInt = Integer.valueOf(userId);
            UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

            userInfo.setTelNum(phoneNumber);
            // 设置手机号
            userInfoService.modifyUserTelNum(userInfo);

        }

        this.connectionInfoService.setNeedByUserId(Integer.valueOf(userId),connectionUserNeedInfo.getNeedIds(),springProfilesActive);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 查询自己已经选择的
     * yl 20200611
     * @param userId
     * @return
     */
    @PostMapping(value = "/selectNeedByUserId", produces = "application/json;charset=UTF-8")
    public RespData selectNeedByUserId(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {
       List<ConnectionNeedInfo> ids = this.connectionInfoService.selectNeedByUserId(Integer.valueOf(userId),springProfilesActive);
        RespData respData = new RespData();
       if (CollectionUtils.isEmpty(ids)){
           respData.setCode(ReturnCode.NORMAL_SUCC);
           return respData;
       }
       Map<String,List<ConnectionNeedInfo>> map = Maps.newHashMap();
        map.put("needId",ids);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(map);
        return respData;
    }

    /**
     * 查询类型基础信息
     * yl 20200611
     * @param userId
     * @return
     */
    @PostMapping(value = "/getArticleType", produces = "application/json;charset=UTF-8")
    public RespData getArticleType(@RequestHeader("userId") String userId) {
        List<ArticleTypeInfo> articleTypeInfo = this.articleTypeInfoService.getArticleTypeInfo();
        RespData respData = new RespData();
        if (CollectionUtils.isEmpty(articleTypeInfo)){
            respData.setCode(ReturnCode.NORMAL_SUCC);
            return respData;
        }
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(articleTypeInfo);
        return respData;
    }


    /**
     * 查询用户关注的类型
     * yl 20200611
     * @param userId
     * @return
     */
    @PostMapping(value = "/getUserConcernArticleTypeInfo", produces = "application/json;charset=UTF-8")
    public RespData getUserConcernArticleTypeInfo(@RequestHeader("userId") String userId) {
        List<Integer> userConcernArticleTypeInfo = this.connectionInfoService.getUserAttentionArticleTypeInfo(Integer.valueOf(userId));
        if (CollectionUtils.isEmpty(userConcernArticleTypeInfo)){
            userConcernArticleTypeInfo = this.userArticleTypeInfoService.getUserConcernArticleTypeInfo(Integer.valueOf(userId));
        }
        RespData respData = new RespData();
        if (CollectionUtils.isEmpty(userConcernArticleTypeInfo)){
            respData.setCode(ReturnCode.NORMAL_SUCC);
            return respData;
        }
        Map<String,List<Integer>> map = Maps.newHashMap();
        map.put("articleTypeId",userConcernArticleTypeInfo);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(map);
        return respData;
    }

    /**
     * 20200601 yl
     * 人脉广场分页查询用户
     * @param userId
     * @param recommendUserInfoReqBean
     * @return
     */
    @PostMapping(value = "/queryUserList", produces = "application/json;charset=UTF-8")
    public RespData queryUserList(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody GetRecommendUserInfoReqBean recommendUserInfoReqBean) {

//        WeixinServiceDL weixinService= objectFactory.getObject();
//        weixinService.reSetConfigStorage(springProfilesActive);
        PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
        //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
        WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

        this.addFriendsOnPlatform(Integer.valueOf(userId),springProfilesActive,weixinService);
        Integer pageNum = recommendUserInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = recommendUserInfoReqBean.getPageSize();
        if (pageSize == null || pageSize.intValue() <= 0) {
            pageSize = 10;
        }

        String[] screen = null;
        if (StringUtils.isNotBlank(recommendUserInfoReqBean.getRegion())){
            screen = StringUtils.split(recommendUserInfoReqBean.getRegion(),',');
        }

        RespData respData = new RespData();
        List<UserInfo> users;
        if (pageNum.equals(1) && recommendUserInfoReqBean.getRegion().length() ==0 && CollectionUtils.isEmpty(recommendUserInfoReqBean.getNeedIds()) && CollectionUtils.isEmpty(recommendUserInfoReqBean.getArticleTypeIds())){
            // vip前6个
            users = this.userInfoService.selectUserList(null,
                    null,
                    Integer.valueOf(userId),
                    springProfilesActive,
                    null,
                    null,
                    null);
            if(users.size() == 6){
                users.addAll(ToolUtil.getMineTwoAndTwo());//插入客服信息
                Collections.shuffle(users);//混乱的意思
            }
        }else {
            if (CollectionUtils.isEmpty(recommendUserInfoReqBean.getNeedIds()) && CollectionUtils.isEmpty(recommendUserInfoReqBean.getArticleTypeIds())){
                pageNum--;
            }

            if (pageNum.equals(1)){
                // 设置基准用户
                Integer standardUserId = userInfoService.selectStandardUserIdByCreationTimeDesc();
                redisTemplate.opsForValue().set(CONNECTIONUSERSTANDARDPREFIX + userId,standardUserId);
            }
            users = this.userInfoService.selectUserListByRandom(pageNum,
                    pageSize,
                    Integer.valueOf(userId),
                    springProfilesActive,
                    screen,
                    recommendUserInfoReqBean.getNeedIds(),
                    recommendUserInfoReqBean.getArticleTypeIds(),
                    (Integer) redisCacheUtil.getCacheObject(CONNECTIONUSERSTANDARDPREFIX + userId));
        }
        if (CollectionUtils.isNotEmpty(users)){
            // 将电话设置为*
            respData.setData( users.stream().map(userInfo -> {
                if (StringUtils.isNotBlank(userInfo.getTelNum()) && userInfo.getTelNum().length() > 4){
                    userInfo.setTelNum(userInfo.getTelNum().replace(userInfo.getTelNum().substring(2,userInfo.getTelNum().length() - 2), "*******"));
                }
                userInfo.setNeedList(this.connectionInfoService.selectNeedNameByUserId(userInfo.getUserId(),springProfilesActive));
                userInfo.setRegion(this.connectionInfoService.selectRegionByUserId(userInfo.getUserId()));
                userInfo.setBrandNames(String.join(",", this.userBrandInfoService.getUserBrandNameInfo(userInfo.getUserId())));
                if(userInfo.getVipStatus() != null && userInfo.getVipStatus() == 1) {
                    userInfo.setVipStatus(1);
                }else {
                    userInfo.setVipStatus(0);
                }
                return userInfo;
            }).collect(Collectors.toList()));
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("请求成功~");
            return respData;
        }
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("暂无数据~");
        return respData;
    }




}
